const express = require("express");
const cors = require("cors");
const joi = require("joi");
const expressJWT = require("express-jwt");
const userRouter = require("./router/user.js");
const cellRouter = require("./router/cell/index.js");
const terminalRouter = require("./router/terminal/index.js");
const sensorRouter = require("./router/sensor/index.js");

const app = express();

const config = require("./config.js");
//跨域
app.use(cors());
//错误处理
app.use(function (req, res, next) {
  res.errorHandler = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err,
    });
  };
  next();
});
//权限api
// app.use(
//   expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//] })
// );
//解析req的body消息
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//路由
app.use("/api", userRouter);
app.use("/api/cell", cellRouter);
app.use("/api/term", terminalRouter);
app.use("/api/sensor", sensorRouter);

app.use(function (err, req, res, next) {
  // 数据验证失败
  if (err instanceof joi.ValidationError) return res.errorHandler(err);
  if (err.name === "UnauthorizedError") {
    return res.errorHandler("token 身份认证失败");
  }
  // next();
});

app.listen(3007, () => {
  console.log("api server running at http://127.0.0.1:3007");
});
